<?php
class ss_data_structure{
	private $structure;
	private $baseQuery;
	private $cache=array();
	private $slugIndex=array();
	private $settings;
	private $table;
	
	public function __construct(ss_core_configInterface $ss_settings){
		$this->settings=$ss_settings;
		$this->table=Doctrine::getTable($this->settings['database']['structure']['table']);
		$this->structure=$this->table->getTree();
	}
	
	public function setBaseQuery($query=null){
		//$_base=$this->table->queryToDQL(array_replace_recursive($this->table->getBaseQuery(),$query));
		//$_query=is_null($query)?$this->table->arrayQuery($query,true,'active');:$this->table->arrayQuery($query,true,'active');
		$_query=$this->table->detectQuery($query,true,'active');
		//ss_error::log($_query,'Structure base qery');
		$this->structure->setBaseQuery($_query);
	}
	
	public function getRoot($tree=1){
		return $this->structure->fetchRoot($tree);
	}
	
	public function getTree($tree=1){
		return $this->structure->fetchTree($tree);
	}
	
	public function getDescendants($node,$levels){
		return $node->getDescendants($levels);
	}
	
	public function getNodeBySlug($slug,$tree=1){
		if(array_key_exists($slug,$this->slugIndex)) return $this->cache[$this->slugIndex[$slug]];
		//ss_error::log($this->slugIndex,'Index');
		//if($node=$this->table->fetchOne($this->table->dqlArrayQuery(array('andWhere'=>array("slug='{$slug}'"))))) return $this->nodeToArray($node);
		if($node=$this->table->queryOne(array('andWhere'=>array("slug='{$slug}'")),2,2)) return $this->nodeToArray($node);
		//ss_error::log($slug,'Get node');
		//if($node=$this->table->query(array('andWhere'=>"slug='{$slug}'"))->getFirst()) return $this->nodeToArray($node);
		return false;
	}
	
	public function getSiblings($node){
		return $node->getSiblings();
	}
	
	public function getNodeById($id,$tree=1){
		if($this->cache[$id]) return $this->cache[$id];
	}
	
	public function getNavStructure($levels=2,$tree=1){
		$dataCollection=$this->structure->fetchTree(array('depth'=>$levels,'root_id'=>$tree));
		$data=$this->collectionToTree($dataCollection);
		return $data;
		$rootNode=$this->getRoot($tree);
		$dataCollection=$rootNode->getNode()->getDescendants($levels);
		$root=$this->nodeToArray($rootNode);
		$data[$rootNode['id']]=$root;
	}
	
	private function collectionToTree($collection){
		ss_error::log(get_class($collection),'Collection');
		$result=array();
		foreach($collection as $node){
			ss_error::log(get_class($node),'Node');
			$row=$this->nodeToArray($node);
			$result[$row['slug']]=$row;
			//print_r($node->getJSONData());
		}
		return $result;
	}
	
	private function nodeToArray($node){
		$data=$node;//->getJSONData();
		//print_r($data);
		//$data=$node->toArray();
		if(!array_key_exists($data['id'],$this->cache)) {
			$this->cache[$data['id']]=$data;
			$this->slugIndex[$data['slug']]=$data['id'];
		}
		return $data;
	}
}
?>